package com.jintoufs.web.action.shiro.realm;


import com.jintoufs.domain.security.Resource;
import com.jintoufs.domain.user.User;
import com.jintoufs.service.security.ResourceService;
import com.jintoufs.service.user.UserService;
import com.jintoufs.web.action.shiro.CaptchaUsernamePasswordToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * <p/>
 * User: Zhang Kaitao
 * <p/>
 * Date: 14-1-28
 * <p/>
 * Version: 1.0
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private ResourceService resourceService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", username);
        List<User> list = userService.queryByParams(params);
        if (list != null && list.size() > 0) {
            Set<String> roles = new HashSet<String>();
            Set<String> permissions = new HashSet<String>();
            User user = list.get(0);
            roles.add(user.getRole().getRoleName());
            authorizationInfo.setRoles(roles);
            List<Resource> listResources = resourceService.selectByRole(user.getRoleId());
            for (Resource resource : listResources) {
                if (resource.getPermission() != null && !"".equals(resource.getPermission())) {
                    permissions.add(resource.getPermission());
                }
            }
            authorizationInfo.setStringPermissions(permissions);
        }

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        CaptchaUsernamePasswordToken captchaUPToken = (CaptchaUsernamePasswordToken) token;
        String username = (String) captchaUPToken.getPrincipal();
        User user = null;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", username);
        List<User> list = userService.queryByParams(params);
        if (list != null && list.size() > 0) {
            user = list.get(0);
        }

        if (user == null) {
            throw new UnknownAccountException();// 没找到帐号
        }

//        if (user.getStatus() == 0) {
//            throw new LockedAccountException(); // 帐号锁定
//        }

        // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), // 用户名
                user.getPassword(), // 密码
                ByteSource.Util.bytes(user.getCredentialsSalt()),// salt=username+salt
                getName() // realm name
        );
        return authenticationInfo;
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }

}
